<template>
  <div>
    <el-row :gutter='20'>
      <el-col :span='16' :offset='4'>
        <el-card style='margin-top: 50px'>
          <div slot='header' class='clearfix'>
            <span>我的分类管理</span>
            <div style='float: right;'>
              <el-button type='warning' icon='el-icon-edit' @click='editDialogVisible = true'
                         size='small'>修改
              </el-button>
              <el-button type='primary' icon='el-icon-circle-plus-outline'
                         @click='addDialogVisible = true' size='small'>添加
              </el-button>
            </div>
          </div>
          <!--展开列-->
          <el-row :class="['',i1 === 0 ? '': 'bdtop','vcenter']" v-for='( item1, i1) in options' :key='item1.id'>
            <!--渲染一级分类-->
            <el-col :span='5'>
              <el-tag closable type='danger' :id='item1.id + "tag"' effect='dark' @close='removeRightByid(item1.id)'>{{ item1.name }}</el-tag>
                <i @click='clickEvent($event)' :id='item1.id' v-if='open_close_show' class='el-icon-caret-right spin-out'></i>
                <!--<img @click="open_close_show = !open_close_show" v-if="open_close_show" src="../../public/image/beauty.png">-->
            </el-col>
            <!--渲染二级、三级分类-->
            <el-col :span='19'>
              <!--通过for循环嵌套渲染二级权限-->
              <el-row :class="[i2 === 0 ? '': 'bdtop','vcenter']" v-for='(item2, i2) in item1.children' :key='item2.id'>
                <el-col :span='6'>
                  <el-tag type='success' :id='item2.id + "tag"' effect='dark' closable @close='removeRightByid(item2.id)'>
                    {{ item2.name }}
                  </el-tag>
                    <i @click='clickEvent($event)' :id='item2.id' v-if='open_close_show' class='el-icon-caret-right spin-out'></i>
                </el-col>
                <el-col :span='18'>
                  <div v-for='(item3) in item2.children' :key='item3.id'>
                    <el-tag effect='dark' type='warning' :id='item3.id + "tag"'
                            closable @close='removeRightByid(item3.id)'>{{ item3.name }}
                    </el-tag>
                  </div>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <!--添加分类对话框-->
    <el-dialog
      title='添加分类'
      :visible.sync='addDialogVisible'
      width='50%'
      @close='addDialogClosed'>
      <!--内容主题区-->
      <el-form :model='addForm' :rules='addFormRules' ref='addFormRef' label-width='80px'>
        <el-form-item label='父级分类' prop='id'>
          <categories-cascader v-on:categoriesCallBack='addCategoryCall' />
          <el-tooltip class='item' effect='dark' content='不填默认为顶级分类' placement='right'>
            <i class='el-icon-info' style='font-size: 30px;vertical-align: middle;margin-left: 2%;'></i>
          </el-tooltip>
        </el-form-item>
        <el-form-item label='分类名称' prop='name'>
          <el-input autofocus placeholder='请输入分类名称' v-model='addForm.name' clearable></el-input>
        </el-form-item>
      </el-form>
      <!--底部按钮区域-->
      <span slot='footer' class='dialog-footer'>
        <el-button @click='addDialogVisible = false'>取 消</el-button>
        <el-button type='primary' @click='addCategory'>确 定</el-button>
      </span>
    </el-dialog>
    <!--修改用户对话框-->
    <el-dialog
      title='修改分类'
      :visible.sync='editDialogVisible'
      width='50%'
      @close='editDialogClosed'>
      <!--内容主题区-->
      <el-form :model='editForm' :rules='editFormRules' ref='editFormRef' label-width='80px'>
        <el-form-item class='category-of-father' label='请选择要修改的分类' label-width='25%' prop='id'>
          <categories-cascader v-on:categoriesCallBack='modifyCategoryCall' />
          <el-tooltip class='item' effect='dark' content='必选项' placement='right'>
            <i class='el-icon-info' style='font-size: 30px;vertical-align: middle;margin-left: 2%;color: red'></i>
          </el-tooltip>
        </el-form-item>
        <el-form-item label='修改后的名称' label-width='25%' prop='name'>
          <el-input autofocus placeholder='请输入修改名称' v-model='editForm.name' clearable></el-input>
        </el-form-item>
      </el-form>
      <!--底部按钮区域-->
      <span slot='footer' class='dialog-footer'>
    <el-button @click='editDialogVisible = false'>取 消</el-button>
    <el-button type='primary' @click='editRoleInfo'>确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import categoriesCascader from '../common/components/categoriesCascader'

export default {
  data () {
    return {
      category: {},
      open_close_show: true,
      inputVisible: false,
      inputValue: '',
      options: [],
      // 控制添加分类对话框的显示与隐藏
      addDialogVisible: false,
      // 控制编辑分类对话框的显示与隐藏
      editDialogVisible: false,
      // 添加分类表单数据
      addForm: {
        id: '',
        name: '',
        length: 0
      },
      // 编辑分类表单数据
      editForm: {
        id: '',
        name: '',
        length: 0
      },
      // 添加表单的验证规则对象
      addFormRules: {
        name: [
          {
            required: true,
            message: '请输入类型名称',
            trigger: 'blur'
          }, {
            max: 20,
            min: 2,
            trigger: 'blur'
          }
        ]
      },
      // 修改表单的验证规则对象
      editFormRules: {
        // 验证id是否为空
        // id: [
        //   {
        //     require: true,
        //     message: '请选择类型',
        //     trigger: 'blur'
        //   }
        // ],
        // 验证分类名称是否合法
        name: [
          {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
          }, {
            max: 10,
            min: 2,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  beforeCreate () {
  },
  created () {
    this.getUserArticleCategory()
  },
  // DOM对象加载完成时
  mounted () {
  },
  methods: {
    // 加载当前用户的文章分类
    async getUserArticleCategory () {
      this.$memory.getUser().then(userString => {
        if (userString === null) {
          return
        }
        const user = JSON.parse(userString)
        // console.log(user)
        const id = user.id
        const url = this.$config.urls.get('load_user_article_category')
        this.$http.post(url, { user_id: id }).then(res => {
          if (res.data.code !== 0) {
            this.$message.error(res.data.error_message)
          }
          this.options = res.data.data
          // this.options.push({
          //   inputVisible: false,
          //   inputValue: ''
          // })
          console.log(this.options)
          // console.log(this.options[this.options.length - 1].inputVisible)
          // console.log(this.options[this.options.length - 1].inputValue)
        }).catch(e => {
          this.$message.error(e)
        })
      })
    },
    // 根据id删除对应的分类
    async removeRightByid (categotyId) {
      // 弹框提示用户是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除！')
      // 发送请求
      const url = this.$config.urls.get('delete_category')
      const { data: res } = await this.$http.post(url, { id: categotyId })
      if (res.code !== 0) return this.$message.error('删除分类失败！')
      this.getUserArticleCategory()
      // 将本地的数据替换成服务器返回地最新数据
      // role.children = res.data
      return this.$message.success('删除分类成功！')
    },
    showInput () {
      this.inputVisible = true
      // this.$nextTick(_ => {
      //   this.$refs.saveTagInput.$refs.input.focus()
      // })
    },
    handleInputConfirm (id) {
      console.log(id)
      const inputValue = this.inputValue
      if (inputValue) {
        this.options.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    addCategoryCall (list) {
      this.addForm.id = list[list.length - 1]
      this.addForm.length = list.length
    },
    modifyCategoryCall (list) {
      this.editForm.id = list[list.length - 1]
      this.editForm.length = list.length
    },
    // 监听添加分类对话框的关闭事件
    addDialogClosed () {
      // 清空表单内容
      this.$refs.addFormRef.resetFields()
    },
    // 监听修改分类对话框的关闭事件
    editDialogClosed () {
      // 清空表单内容
      this.$refs.editFormRef.resetFields()
    },
    // 点击按钮修改新分类
    editRoleInfo () {
      console.log(this.editForm)
      // console.log(this.$refs.editFormRef)
      this.$refs.editFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) {
          return this.$message.info('验证失败')
        } else {
          // 可以发起添加用户的网络请求
          const url = this.$config.urls.get('update_category')
          // console.log(this.editForm)
          // console.log(this.editForm.id[this.editForm.id.length - 1])
          if (this.editForm.id === null || this.editForm.id === '') {
            return this.$message.error('请先选择分类！！！')
          }
          const { data: res } = await this.$http.post(url, {
            id: this.editForm.id,
            name: this.editForm.name
          })
          // console.log(res)
          if (res.data.code !== 0) this.$message.error('修改分类信息失败！')
          this.$message.success('更新分类信息成功！')
          // 隐藏编辑分类的对话框
          this.editDialogVisible = false
          // 重新获取分类列表数据
          this.getUserArticleCategory()
        }
      })
    },
    // 点击按钮添加分类
    addCategory () {
      this.$refs.addFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) {
          return this.$message.info('验证失败')
        } else {
          // 可以发起添加用户的网络请求
          const url = this.$config.urls.get('add_category')
          console.log(this.addForm.id)
          if (this.addForm.length >= 3) {
            return this.$message.error('不能在三级分类之后添加分类！')
          }
          const { data: res } = await this.$http.post(url, {
            name: this.addForm.name,
            parent_id: this.addForm.id
          })
          // console.log(res)
          if (res.data.code !== 0) {
            this.$message.error('添加分类失败！')
          }
          this.$message.success('添加分类成功！')
          // 隐藏添加用户的对话框
          this.addDialogVisible = false
          // 重新获取用户文章分类列表数据
          await this.getUserArticleCategory()
        }
      })
    },
    clickEvent (e) {
      const id = e.currentTarget.id
      console.log(e.currentTarget)
      let result = null
      // 是否为树的子项
      let isFirst = false
      // console.log(e.currentTarget.classList)
      if (e.currentTarget.classList.contains('spin-in')) {
        result = this.recursionFindObj(this.options, id)
        // console.log(result)
        e.currentTarget.classList.remove('spin-in')
        e.currentTarget.classList.add('spin-out')
        // ********************以下是一样的代码**********************
        // 判断是否为树的子项
        this.options.forEach(item => {
          if (item === result) {
            isFirst = true
          }
        })
        // console.log(isFirst)
        // 如果是树的子项
        if (isFirst) {
          console.log(result)
          result.children.forEach(item => {
            const tagElement = document.getElementById(item.id + 'tag')
            // console.log(tagElement)
            this.controlFade(tagElement)
            item.children.forEach(item2 => {
              const tagElement = document.getElementById(item2.id + 'tag')
              this.controlFade(tagElement)
            })
          })
        } else {
          // 去除三角后的子tag
          result.children.forEach(item => {
            const tagElement = document.getElementById(item.id + 'tag')
            this.controlFade(tagElement)
          })
        }
      } else {
        result = this.recursionFindObj(this.options, id)
        // console.log(result)
        e.currentTarget.classList.remove('spin-out')
        e.currentTarget.classList.add('spin-in')
        // ********************以下是一样的代码**********************
        // 判断是否为树的子项
        this.options.forEach(item => {
          if (item === result) {
            isFirst = true
          }
        })
        console.log(isFirst)
        // 如果是树的子项,则隐藏所有
        if (isFirst) {
          console.log(result)
          result.children.forEach(item => {
            const tagElement = document.getElementById(item.id + 'tag')
            // console.log(tagElement)
            this.controlFade(tagElement)
            item.children.forEach(item2 => {
              const tagElement = document.getElementById(item2.id + 'tag')
              this.controlFade(tagElement)
            })
          })
        } else {
          // 去除三角后的子tag
          result.children.forEach(item => {
            const tagElement = document.getElementById(item.id + 'tag')
            this.controlFade(tagElement)
          })
        }
      }
      const html = e.currentTarget.parentNode.parentNode.childNodes[e.currentTarget.parentNode.parentNode.childNodes.length - 1]
      if (html.style.display === 'none') {
        html.style.display = 'block'
      } else {
        html.style.display = 'none'
      }

      // console.log(e.currentTarget.parentNode.parentNode.childNodes[e.currentTarget.parentNode.parentNode.childNodes.length - 1])
      // console.log(e.currentTarget.parentElement)
      // console.log(e.currentTarget.children)
    },
    recursionFindObj (data, id) {
      let result = null
      if (!data) {
        // return; 中断执行
        return
      }
      for (const i in data) {
        // 已经找到了属性值所在的对象就终止循环,以免后面的循环覆盖result,导致出错
        if (result !== null) {
          break
        }
        var item = data[i]
        if (item.id === id) {
          result = item
          break
        } else if (item.children) {
          result = this.recursionFindObj(item.children, id)
        }
      }
      return result
    },
    // 控制三角后的tag淡入淡出
    controlFade (element) {
      if (element.classList.contains('fade-in')) {
        element.classList.remove('fade-in')
        element.classList.add('fade-out')
      } else if (element.classList.contains('fade-out')) {
        element.classList.remove('fade-out')
        element.classList.add('fade-in')
      } else {
        element.classList.add('fade-out')
      }
    }
  },
  computed: {},
  name: 'categoryManager',
  components: { categoriesCascader }
}
</script>

<style lang='less' scoped>
.el-tag {
  margin: 7px
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}

.button-new-tag {
  margin: 7px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin: 7px;
  vertical-align: bottom;
}
/deep/.el-form-item__content {
  display: flex;
  align-items: center;
}
.el-button--warning {
  color: #FFF;
  background-color: #f78989;
  border-color: #f78989;
}

.el-button--warning:focus, .el-button--warning:hover {
  color: #FFF;
  background-color: #f78989;
  border-color: #f78989;
}
.spin-in{
  animation: spin-in 0.5s 1 linear forwards;
}
.spin-out{
  animation: spin-out 0.5s 1 linear forwards;
}
.fade-out{
  animation: fade-out 2s linear forwards;
}
.fade-in{
  animation: fade-in 2s linear forwards;
}
/*************************动画************************/
@keyframes spin-in {
  0% {transform:rotate(0deg);}
  100%{transform:rotate(180deg);}
}
@keyframes spin-out {
  0% {transform:rotate(180deg);}
  100%{transform:rotate(0deg);}
}
@keyframes fade-out {
  from{opacity: 1}
  to{opacity: 0;}
}
@keyframes fade-in {
  from{opacity: 0}
  to{opacity: 1}
}
</style>
